package org.prs.web.servlet;

import com.prs.util.DateUtil;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.validator.GenericValidator;
import org.prs.model.User;
import org.prs.persistence.UserDatabasePersitenceManager;
import org.prs.service.PasswordService;

public class UserUpdateServlet extends HttpServlet {

    private final String CALL_UPDATE_USER = "updateuser";
    private final String CALL_DELETE_USER = "deleteuser";
    private User user = new User();
    private UserDatabasePersitenceManager persistUser = new UserDatabasePersitenceManager();

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String call = request.getPathInfo().substring(1);
        HttpSession session = request.getSession(true);
        try {
            if (CALL_DELETE_USER.equals(call)) {
                int userId = Integer.parseInt(request.getParameter("userid"));
                if (persistUser.deleteUser(userId)) {
                    response.sendRedirect(request.getContextPath() + "/listUsers.jsp");
                } else {
                    response.sendRedirect(request.getContextPath() + "/listUsers.jsp");
                }
            } else if (CALL_UPDATE_USER.equals(call)) {
                StringBuilder validationMessage = new StringBuilder();
                boolean valid = true;
                user = persistUser.getUserByUserId(Integer.parseInt(request.getParameter("userid")));
                if(GenericValidator.isBlankOrNull(user.getDateRegistered().toString())){
                    user.setDateRegistered(DateUtil.getTodayAsStringYMD2());
                }
                user.setFirstName(request.getParameter("firstname"));
                if (GenericValidator.isBlankOrNull(user.getFirstName())) {
                    valid = false;
                    validationMessage.append("<div id='inputerror'>First Name is null</div>");
                }
                user.setLastName(request.getParameter("lastname"));
                if (GenericValidator.isBlankOrNull(user.getLastName())) {
                    valid = false;
                    validationMessage.append("<div id='inputerror'>Last Name is null</div>");
                }
                user.setMiddleName(request.getParameter("middlename"));
                if (!GenericValidator.isBlankOrNull(request.getParameter("password"))) {
                    if (request.getParameter("password").equals(request.getParameter("confirmpassword"))) {
                        user.setPassword(PasswordService.getInstance().encrypt(request.getParameter("password")));
                    } else {
                        valid = false;
                        validationMessage.append("<div id='inputerror'>Password and confirm Password are not the same</div>");
                    }
                }
                try{
                    user.setUserLevel(Integer.parseInt(request.getParameter("userlevel")));
                }catch(NumberFormatException e){
                    
                }
                if (valid) {
                    if (persistUser.updateUser(user)) {
                        response.sendRedirect(request.getContextPath() + "/viewUser.jsp?userid=" + user.getUserId());
                    } else {
                        session.setAttribute("usereditmsg", "<div id='inputerror'>User was not updated successfully</div>");
                        response.sendRedirect(request.getContextPath() + "/editUser.jsp?userid=" + user.getUserId());
                    }

                } else {
                    request.setAttribute("user", user);
                    session.setAttribute("usereditmsg", validationMessage.toString());
                    response.sendRedirect(request.getContextPath() + "/editUser.jsp?userid=" + user.getUserId());
                }
            }
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
